//
//  GroupViewController.m
//  糗事百科
//
//  Created by 奚超明 on 16/5/31.
//  Copyright © 2016年 奚超明. All rights reserved.
//

#import "GroupViewController.h"
#import "NearbyGroupCell.h"
#import "TiantiGroupCell.h"
#import "GroupModel.h"

@interface GroupViewController () <UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>
/** 附近的群 */
@property (nonatomic, weak) UIButton *nearbyGroup;
/** 群天梯 */
@property (nonatomic, weak) UIButton *tiantiGroup;
/** 指示器 */
@property (nonatomic, weak) UIView *selectView;
/** scrollView */
@property (nonatomic, weak) UIScrollView *scrollView;
/** 附近的群tableview */
@property (nonatomic, weak) UITableView *nearbyGTableView;
/** 群天梯tableview */
@property (nonatomic, weak) UITableView *tiantiGTableView;
/** 记录指示器的初始位置 */
@property (nonatomic, assign) CGFloat selectViewX;
/** 附近群数组 */
@property (nonatomic, strong) NSMutableArray *nearbyGArr;
/** 群天梯数组 */
@property (nonatomic, strong) NSMutableArray *tiantiGArr;
/** 附近的群加载的当前页码 */
@property (nonatomic, assign) NSUInteger nearbyGPage;
/** 群天梯加载的当前页码 */
@property (nonatomic, assign) NSUInteger tiantiGPage;

@end

@implementation GroupViewController

static NSString * const nearbyGID = @"nearbyG";
static NSString * const tiantiGID = @"tiantiG";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 界面初始化
    [self setupView];
    
    // 添加刷新控件
    [self addRefresh];
}

#pragma mark - 界面初始化
- (void)setupView
{
    // 背景色
    self.view.backgroundColor = kRGBColor(255, 255, 255);
    
    // 标题
    self.navigationItem.title = @"群";
    
    // 附近的群
    UIButton *nearbyGroup = [self addGroupBtnWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width / 2, 44) title:@"附近的群" action:@selector(nearbyGroupAction:)];
    self.nearbyGroup = nearbyGroup;
    
    // 群天梯
    UIButton *tiantiGroup = [self addGroupBtnWithFrame:CGRectMake(nearbyGroup.xcm_width, 64, [UIScreen mainScreen].bounds.size.width / 2, 44) title:@"群天梯" action:@selector(tiantiGroupAction:)];
    self.tiantiGroup = tiantiGroup;
    
    // 设置附近的群为默认选中状态
    self.nearbyGroup.selected = YES;
    self.nearbyGroup.userInteractionEnabled = NO;
    
    // 指示器
    CGFloat selectViewWidth = self.nearbyGroup.xcm_width * 0.5;
    CGFloat selectViewHeight = 3;
    CGFloat selectViewX = (self.nearbyGroup.xcm_width - selectViewWidth) * 0.5;
    CGFloat selectViewY = self.nearbyGroup.xcm_height - selectViewHeight + 64;
    UIView *selectView = [[UIView alloc] initWithFrame:CGRectMake(selectViewX, selectViewY, selectViewWidth, selectViewHeight)];
    selectView.backgroundColor = kOrangerColor;
    [self.view addSubview:selectView];
    self.selectView = selectView;
    
    // 指示器初始位置
    self.selectViewX = selectViewWidth * 0.5;
    
    // 分割线
    CGFloat grayLineWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat grayLineHeight = 1;
    CGFloat grayLineX = 0;
    CGFloat grayLineY = self.selectView.xcm_y + self.selectView.xcm_height - grayLineHeight;
    UIView *grayLine = [[UIView alloc] initWithFrame:CGRectMake(grayLineX, grayLineY, grayLineWidth, grayLineHeight)];
    grayLine.backgroundColor = [UIColor lightGrayColor];
    grayLine.alpha = 0.4;
    [self.view addSubview:grayLine];
    
    // scrollview
    CGFloat scrollViewWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat scrollViewHeight = [UIScreen mainScreen].bounds.size.height - self.nearbyGroup.xcm_y - self.nearbyGroup.xcm_height;
    CGFloat scrollViewX = 0;
    CGFloat scrollViewY = self.nearbyGroup.xcm_y + self.nearbyGroup.xcm_height;
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(scrollViewX, scrollViewY, scrollViewWidth, scrollViewHeight)];
    scrollView.contentSize = CGSizeMake(2 * [UIScreen mainScreen].bounds.size.width, 0);
    scrollView.pagingEnabled = YES;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.delegate = self;
    [self.view addSubview:scrollView];
    self.scrollView = scrollView;
    
    // 附近的群tableview
    UITableView *nearbyGTableView = [self addTableViewWithFrame:CGRectMake(0, 0, self.scrollView.xcm_width, self.scrollView.xcm_height) tableViewCell:[NearbyGroupCell class] identifier:nearbyGID];
    nearbyGTableView.rowHeight = 90;
    self.nearbyGTableView = nearbyGTableView;
    
    // 群天梯tableview
    UITableView *tiantiGTableView = [self addTableViewWithFrame:CGRectMake(self.scrollView.xcm_width, 0, self.scrollView.xcm_width, self.scrollView.xcm_height) tableViewCell:[TiantiGroupCell class] identifier:tiantiGID];
    tiantiGTableView.rowHeight = 90;
    self.tiantiGTableView = tiantiGTableView;
}

#pragma mark - 添加tableView
- (UITableView *)addTableViewWithFrame:(CGRect)frame tableViewCell:(Class)tableViewCell identifier:(NSString *)identifier
{
    UITableView *tableView = [[UITableView alloc] initWithFrame:frame];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.delegate = self;
    tableView.dataSource = self;
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass(tableViewCell) bundle:nil] forCellReuseIdentifier:identifier];
    [self.scrollView addSubview:tableView];
    return tableView;
}

#pragma mark - 添加不同分类群的Button
- (UIButton *)addGroupBtnWithFrame:(CGRect)frame title:(NSString *)title action:(SEL)action
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    button.titleLabel.font = [UIFont systemFontOfSize:12];
    button.backgroundColor = kRGBColor(255, 255, 255);
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateSelected];
    [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    return button;
}

#pragma mark - 添加刷新控件
- (void)addRefresh
{
    // 下拉刷新控件
    self.nearbyGTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tiantiGTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    // 上拉刷新控件
    self.nearbyGTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tiantiGTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    // 当前加载的页码
    self.nearbyGPage = 1;
    self.tiantiGPage = 1;
    
    // 一开始下拉刷新
    [self.nearbyGTableView.mj_header beginRefreshing];
}

#pragma mark - 下拉刷新添加新数据
- (void)loadNewData
{
    // 记录此时偏移量
    CGFloat offsetX = self.scrollView.contentOffset.x;
    
    // 根据偏移量判断当前显示的tableview
    if (offsetX == 0) { // 附近的群tableview
        // 停止群天梯tableview的所有刷新
        [self.tiantiGTableView.mj_header endRefreshing];
        [self.tiantiGTableView.mj_footer endRefreshing];
        
        // 停止附近的群tableview的上拉刷新
        [self.nearbyGTableView.mj_footer endRefreshing];
        
        // 移除附近的群所有数据
        [self.nearbyGArr removeAllObjects];
        
        // 页码变为1
        self.nearbyGPage = 1;
        
        NSString *file = [[NSBundle mainBundle] pathForResource:@"groupNearby1" ofType:@"json"];
        NSData *data = [NSData dataWithContentsOfFile:file];
        NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArr = rootDic[@"data"];
        for (NSDictionary *modelDic in dataArr) {
            GroupModel *model = [GroupModel groupWithDic:modelDic];
            [self.nearbyGArr addObject:model];
        }
        
        [self.nearbyGTableView reloadData];
        [self.nearbyGTableView.mj_header endRefreshing];
    } else { // 群天梯tableview
        // 停止附近的群tableview的所有刷新
        [self.nearbyGTableView.mj_header endRefreshing];
        [self.nearbyGTableView.mj_footer endRefreshing];
        
        // 停止群天梯tableview的上拉刷新
        [self.tiantiGTableView.mj_footer endRefreshing];
        
        // 移除附近的群所有数据
        [self.tiantiGArr removeAllObjects];
        
        // 页码变为1
        self.tiantiGPage = 1;
        
        NSString *file = [[NSBundle mainBundle] pathForResource:@"groupTianti1" ofType:@"json"];
        NSData *data = [NSData dataWithContentsOfFile:file];
        NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArr = rootDic[@"data"];
        for (NSDictionary *modelDic in dataArr) {
            GroupModel *model = [GroupModel groupWithDic:modelDic];
            [self.tiantiGArr addObject:model];
        }
        
        [self.tiantiGTableView reloadData];
        [self.tiantiGTableView.mj_header endRefreshing];
    }
}

#pragma mark - 上拉刷新添加更多数据
- (void)loadMoreData
{
    // 记录此时偏移量
    CGFloat offsetX = self.scrollView.contentOffset.x;
    
    // 根据偏移量判断当前显示的tableview
    if (offsetX == 0) { // 附近的群tableview
        // 停止群天梯tableview的所有刷新
        [self.tiantiGTableView.mj_header endRefreshing];
        [self.tiantiGTableView.mj_footer endRefreshing];
        
        // 停止附近的群tableview的下拉刷新
        [self.nearbyGTableView.mj_header endRefreshing];
        
        // 页码增加1
        self.nearbyGPage++;
        
        NSString *file = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"groupNearby%zd", self.nearbyGPage] ofType:@"json"];
        NSData *data = [NSData dataWithContentsOfFile:file];
        NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArr = rootDic[@"data"];
        for (NSDictionary *modelDic in dataArr) {
            GroupModel *model = [GroupModel groupWithDic:modelDic];
            [self.nearbyGArr addObject:model];
        }
        
        [self.nearbyGTableView reloadData];
        
        if (self.nearbyGPage >= 4) {
            [self.nearbyGTableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.nearbyGTableView.mj_footer endRefreshing];
        }
    } else { // 群天梯tableview
        // 停止附近的群tableview的所有刷新
        [self.nearbyGTableView.mj_header endRefreshing];
        [self.nearbyGTableView.mj_footer endRefreshing];
        
        // 停止群天梯tableview的下拉刷新
        [self.tiantiGTableView.mj_header endRefreshing];
        
        // 页码增加1
        self.tiantiGPage++;
        
        NSString *file = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"groupTianti%zd", self.tiantiGPage] ofType:@"json"];
        NSData *data = [NSData dataWithContentsOfFile:file];
        NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArr = rootDic[@"data"];
        for (NSDictionary *modelDic in dataArr) {
            GroupModel *model = [GroupModel groupWithDic:modelDic];
            [self.tiantiGArr addObject:model];
        }
        
        [self.tiantiGTableView reloadData];
        
        if (self.tiantiGPage >= 9) {
            [self.tiantiGTableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.tiantiGTableView.mj_footer endRefreshing];
        }
    }

}

#pragma mark - 返回行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.nearbyGTableView) {
        return self.nearbyGArr.count;
    } else {
        return self.tiantiGArr.count;
    }
}

#pragma mark - 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.nearbyGTableView) {
        NearbyGroupCell *cell = [tableView dequeueReusableCellWithIdentifier:nearbyGID];
        cell.model = self.nearbyGArr[indexPath.row];
        return cell;
    } else {
        TiantiGroupCell *cell = [tableView dequeueReusableCellWithIdentifier:tiantiGID];
        cell.model = self.tiantiGArr[indexPath.row];
        return cell;
    }
}

#pragma mark - 滚动时调用的方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([scrollView isMemberOfClass:[UITableView class]]) {
        return;
    }
    // 记录偏移量
    CGFloat offsetX = scrollView.contentOffset.x;
    
    self.selectView.xcm_x = self.selectViewX;
    
    // 改变指示器的位置
    self.selectView.xcm_x += offsetX * 0.5;
}

#pragma mark - 结束动画
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    // 记录此时的偏移量
    CGFloat offsetX = scrollView.contentOffset.x;
    
    if (offsetX == 0) { // 附近的群
        if (self.nearbyGArr.count == 0) { // 没有数据则默认下拉刷新
            [self.nearbyGTableView.mj_header beginRefreshing];
        }
    } else { // 群天梯
        if (self.tiantiGArr.count == 0) {
            [self.tiantiGTableView.mj_header beginRefreshing];
        }
    }
}

#pragma mark - 结束减速
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 记录此时的偏移量
    CGFloat offsetX = scrollView.contentOffset.x;
    
    if (offsetX == 0) { // 附近的群
        // 改变此时选择的Button
        self.nearbyGroup.selected = YES;
        self.nearbyGroup.userInteractionEnabled = NO;
        self.tiantiGroup.selected = NO;
        self.tiantiGroup.userInteractionEnabled = YES;
    } else { // 群天梯
        // 改变此时选择的Button
        self.tiantiGroup.selected = YES;
        self.tiantiGroup.userInteractionEnabled = NO;
        self.nearbyGroup.selected = NO;
        self.nearbyGroup.userInteractionEnabled = YES;
    }
    
    [self scrollViewDidEndScrollingAnimation:scrollView];
}

#pragma mark - 点击了群天梯
- (void)tiantiGroupAction:(UIButton *)button
{
    self.tiantiGroup.selected = YES;
    self.tiantiGroup.userInteractionEnabled = NO;
    
    self.nearbyGroup.selected = NO;
    self.nearbyGroup.userInteractionEnabled = YES;
    
    // 改变指示器位子
    [UIView animateWithDuration:0.2 animations:^{
        self.selectView.xcm_x += [UIScreen mainScreen].bounds.size.width * 0.5;
    }];
    
    // 改变偏移量
    [self.scrollView setContentOffset:CGPointMake([UIScreen mainScreen].bounds.size.width, 0) animated:YES];
}

#pragma mark - 点击了附近的群
- (void)nearbyGroupAction:(UIButton *)button
{
    self.nearbyGroup.selected = YES;
    self.nearbyGroup.userInteractionEnabled = NO;
    
    self.tiantiGroup.selected = NO;
    self.tiantiGroup.userInteractionEnabled = YES;
    
    // 改变指示器位置
    [UIView animateWithDuration:0.2 animations:^{
        self.selectView.xcm_x -= [UIScreen mainScreen].bounds.size.width * 0.5;
    }];
    
    // 改变偏移量
    [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

#pragma mark - 懒加载
- (NSMutableArray *)nearbyGArr
{
    if (!_nearbyGArr) {
        _nearbyGArr = [NSMutableArray array];
    }
    return _nearbyGArr;
}

- (NSMutableArray *)tiantiGArr
{
    if (!_tiantiGArr) {
        _tiantiGArr = [NSMutableArray array];
    }
    return _tiantiGArr;
}
@end
